<script lang="ts">
// 工艺路线
export default {
  name: "workmanshipPage",
  components: { addProcessRoute }
};
</script>
<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import addProcessRoute from "/@/views/basic/workmanship/addProcessRoute.vue";
import { VXETable, VxeTableInstance, VxeToolbarInstance } from "vxe-table";
import {
  getWorkmanshipPage,
  downloadTemplete,
  deleteProcesRouteById,
  exportProcessRoute
} from "/@/api/basic/workmanship";
import { successMessage, errorMessage } from "/@/utils/message";
import { useRoute } from "vue-router";
import { loadEnv } from "@build/index";
import { getToken } from "/@/utils/auth";

const route = useRoute();
const routeName = route.name as string;
// 加载环境变量 VITE_PROXY_DOMAIN（开发环境）  VITE_PROXY_DOMAIN_REAL（打包后的线上环境）
const { VITE_PROXY_DOMAIN, VITE_PROXY_DOMAIN_REAL } = loadEnv();
const actionUrl =
  process.env.NODE_ENV === "production"
    ? VITE_PROXY_DOMAIN_REAL
    : (VITE_PROXY_DOMAIN as string);

const getTo = getToken();
const token = JSON.parse(getTo).accessToken as string;
// 上传文件时的token
const myHeaders = reactive({
  Authorization: token
});
const upload = ref();
const page = reactive({
  pageNum: 1,
  pageRow: 20,
  totalResult: 0
});
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    code: "",
    name: ""
  }
});

// 查询
const searchEvent = () => {
  const data: any = {};
  data.name = table.listQuery.name;
  data.code = table.listQuery.code;
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  table.loading = true;
  getWorkmanshipPage(data)
    .then((res: any) => {
      if (res.code === 0) {
        table.tableData = res.data.list;
        page.totalResult = res.data.total;
      }
      table.loading = false;
    })
    .catch(() => {
      errorMessage("查询失败");
      table.loading = false;
    });
};

// 分页发生改变时会触发该事件
const handlePageChange = ({ currentPage, pageSize }) => {
  page.pageNum = currentPage;
  page.pageRow = pageSize;
  searchEvent();
};

const xTable = ref({} as VxeTableInstance);
const xToolbar = ref({} as VxeToolbarInstance);

// 文件上传成功
const fileSuccess = data => {
  if (data.code === 0) {
    successMessage("上传成功");
    searchEvent();
  } else {
    errorMessage(data.message);
  }
  upload.value.clearFiles();
};
// 文件上传失败
const fileError = () => {
  errorMessage("上传失败");
};
// 文件上传前
const fileBefore = file => {
  const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
  const whiteList = ["xlsx", "xls"];
  if (whiteList.indexOf(fileSuffix) === -1) {
    errorMessage("传文件只能是xlsx,xls格式");
    return false;
  }
};
// 下载模板
const download = () => {
  downloadTemplete().then((res: any) => {
    if (res.code == 500) {
      errorMessage(res.message);
    } else {
      const fileBlob = res;
      const fileUrl = URL.createObjectURL(fileBlob); //将blob转成url地址
      const element = document.createElement("a");
      element.setAttribute("href", fileUrl);
      element.setAttribute("downLoad", "工艺路线模板.xls");
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
    }
  });
};
// 导出数据
const exportProcess = () => {
  exportProcessRoute().then((res: any) => {
    if (res.code == 500) {
      errorMessage(res.message);
    } else {
      const fileBlob = res;
      const fileUrl = URL.createObjectURL(fileBlob); //将blob转成url地址
      const element = document.createElement("a");
      element.setAttribute("href", fileUrl);
      element.setAttribute("downLoad", "工艺路线.xls");
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
    }
  });
};

// 新增升级工艺路线
const addProcessDialog = ref(false);
const processDetailId = ref(0);
const processDialogShow = id => {
  addProcessDialog.value = true;
  processDetailId.value = id;
};
const processDialogClose = () => {
  addProcessDialog.value = false;
  processDetailId.value = 0;
};
// 删除工艺路线
const deleteData = async (id: any) => {
  const type = await VXETable.modal.confirm("您确定要删除该数据?");
  if (type === "confirm") {
    deleteProcesRouteById(id).then((res: any) => {
      if (res.code === 0) {
        searchEvent();
        successMessage("删除成功");
      } else {
        errorMessage(res.message);
      }
    });
  }
};

// mounted
onMounted(() => {
  nextTick(() => {
    searchEvent();
    table.tableHeight = changeHeight();
  });
});
</script>

<template>
  <div>
    <!-- 工具栏 -->
    <vxe-form :data="table.listQuery">
      <vxe-form-item title="料号" field="code">
        <template #default="{ data }">
          <vxe-input v-model="data.code" placeholder="请输入料号"></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="品名">
        <template #default="{ data }">
          <vxe-input v-model="data.name" placeholder="请输入品名"></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button
            icon="fa fa-search"
            status="primary"
            @click="searchEvent"
            v-auth="routeName + ':search'"
            >查询</vxe-button
          >
          <vxe-button
            icon="fa fa-plus"
            status="primary"
            @click="processDialogShow(0)"
            v-auth="routeName + ':add'"
            >新增</vxe-button
          >
          <vxe-button
            @click="download"
            status="primary"
            icon="fa fa-download"
            v-auth="routeName + ':download'"
            >下载模板</vxe-button
          >
          <el-upload
            ref="upload"
            class="upload-file"
            :headers="myHeaders"
            :action="actionUrl + '/process-route/upload'"
            v-auth="routeName + ':upload'"
            :limit="1"
            :auto-upload="true"
            :show-file-list="false"
            :on-success="fileSuccess"
            :on-error="fileError"
            :before-upload="fileBefore"
            style="display: contents"
          >
            <vxe-button status="primary" icon="fa fa-upload"
              >导入数据</vxe-button
            >
          </el-upload>
          <vxe-button
            @click="exportProcess"
            status="primary"
            icon="fa fa-download"
            v-auth="routeName + ':download'"
            >导出数据</vxe-button
          >
        </template>
      </vxe-form-item>
    </vxe-form>
    <!-- 列表 -->
    <vxe-table
      ref="xTable"
      class="mytable-style"
      border
      show-header-overflow
      show-overflow
      :row-config="{ isHover: true }"
      :import-config="{}"
      :export-config="{}"
      :print-config="{}"
      :height="table.tableHeight"
      :data="table.tableData"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="code" title="料号" min-width="130"></vxe-column>
      <vxe-column field="name" title="品名" min-width="200"></vxe-column>
      <vxe-column
        field="figureNumber"
        title="别名"
        min-width="150"
      ></vxe-column>
      <vxe-column field="modelNumber" title="机型" min-width="150"></vxe-column>
      <!-- <vxe-column field="version" title="版本号" min-width="100"></vxe-column> -->
      <vxe-column
        field="processStepList"
        title="工序列表"
        min-width="200"
      ></vxe-column>
      <!-- <vxe-column title="工序列表"
                  field="processStepList"> -->
      <!-- <template #default="{ row }"> -->
      <!-- <span v-for="(itemo, index) in row.items"
                :key="itemo.id"
                v-text="
              index < row.items.length - 1 ? itemo.name + ',' : itemo.name
            "></span> -->

      <!-- </template> -->
      <!-- </vxe-column> -->
      <vxe-column title="操作" width="150" fixed="right">
        <template #default="{ row }">
          <vxe-button
            type="text"
            icon="fa fa-edit"
            @click="processDialogShow(row.id)"
            v-auth="routeName + ':edit'"
            >修改</vxe-button
          >
          <vxe-button
            type="text"
            icon="fa fa-trash-o"
            @click="deleteData(row.id)"
            v-auth="routeName + ':delete'"
            >删除</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 分页 -->
    <vxe-pager
      perfect
      @page-change="handlePageChange"
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageRow"
      :total="page.totalResult"
      :page-sizes="[10, 20, 50, 100, 300]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
    >
    </vxe-pager>
    <!-- 弹框弹框添加、升级工艺路线 -->
    <add-process-route
      :dialogShow="addProcessDialog"
      :detailId="processDetailId"
      @processDialogClose="processDialogClose"
      @searchEvent="searchEvent"
    ></add-process-route>
  </div>
</template>
<style scoped>
@import url("/@/style/dialog.css");
</style>

<style>
.mytable-style .vxe-body--column.col-blue {
  background-color: #60b8ff;
  color: #fff;
}
.mytable-style .vxe-body--column.col-orange {
  background-color: #f56c6c;
  color: #fff;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

// .vxe-button.type--button:not(.is--round) {
//   border-radius: 0;
// }

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-table--render-default.size--medium {
  margin-top: 12px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
</style>
